// 用户相关的仓库
import {defineStore} from "pinia";
import {constRoutes, asyncRoute, anyRoute} from "@/router/constRoutes.ts";
import {loginAPI, getUserInfoAPI, logoutAPI} from "@/api/user/index.ts";
import type {loginForm, loginResponseData, userInfo} from "@/api/user/type.ts";
import {Ref, ref, UnwrapRef} from "vue";
import router from '@/router';

// 过滤异步路由
function filterRouter(asyncRoute:any, userRouters:any) {
    return asyncRoute.filter(item => {
        if (userRouters.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterRouter(item.children,userRouters);
            }
            return true;
        }
    })
}

export default defineStore("user", () => {
    let test: any = ref({demo: "123"});
    let user: Ref<UnwrapRef<{ username: string; avatar: string; token: string }>> = ref({
        username: "",
        avatar: "",
        token: ""
    });
    // 菜单
    let routers: any = ref([]);
    // 按钮
    let btn: string[] = ref([]);
    const login = async (data: loginForm) => {
        const result: loginResponseData = await loginAPI(data);
        if (result.data.code === 200) {
            user.value.token = result.data.data;
            localStorage.setItem("user", JSON.stringify(user.value));

            return "ok";
        } else {
            return Promise.reject(result.data.message);
        }
    };

    const getUserInfo = async () => {
        const result: userInfo = await getUserInfoAPI();
        if (result.data.code === 200) {
            user.value.username = result.data.data.name;
            user.value.avatar = result.data.data.avatar;

            btn.value = result.data.data.buttons;
            // 路由处理
            let userAsyncRouters = filterRouter(asyncRoute, result.data.data.routes);
            routers.value = [...constRoutes, ...userAsyncRouters, ...anyRoute];
            [...userAsyncRouters, ...anyRoute].forEach(item => {
                router.addRoute(item);
            });

            return "ok";
        } else {
            return Promise.reject(new Error(result.data.message));
        }
    }
    const logout = async () => {
        const result: any = await logoutAPI();
        if (result.data.code == 200) {
            user.value.username = "";
            user.value.avatar = "";
            user.value.token = "";
            localStorage.removeItem("user");
            return "ok";
        } else {
            return Promise.reject(new Error(result.data.message));
        }
    }
    return {user, test, routers,btn, login, getUserInfo, logout};
});
